import datetime
import json
from django.core.paginator import Paginator, EmptyPage
from django.db.models import Q
from homes.models import House, HouseImage, Facility, Area
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from ihome.utils.view import LoginRequiredMixin
from order.models import Order
from users.models import User


class AreasListView(View):

    def get(self, request):
        '''获取地区列表'''
        # 1.获取数据库所有地区数据
        try:
            areas = Area.objects.all()
        except Exception as e:
            return JsonResponse({"errno": "4001",
                                 "errmsg": "数据库查询错误"})
        # 2.创建列表
        area_list = []
        # 3.遍历areas，这里成字典，添加到列表
        for area in areas:
            area_list.append({
                "aid": area.id,
                "aname": area.name
            })

        # 4.返回
        return JsonResponse({
            "errmsg": "获取成功",
            "errno": "0",
            "data": area_list
        })


class NewHousesInfoView(LoginRequiredMixin, View):

    def post(self, request):
        '''发布新房源'''

        # 1.接收参数
        dict = json.loads(request.body.decode())
        title = dict.get('title')
        price = dict.get('price')
        area_id = dict.get('area_id')
        address = dict.get('address')
        room_count = dict.get('room_count')
        acreage = dict.get('acreage')
        unit = dict.get('unit')
        capacity = dict.get('capacity')
        beds = dict.get('beds')
        deposit = dict.get('deposit')
        min_days = dict.get('min_days')
        max_days = dict.get('max_days')
        facility_list = dict.get('facility')

        # 2.整体检验
        if not all([title, price, area_id,
                    address, room_count, acreage,
                    unit, capacity, beds, deposit,
                    min_days, max_days, facility_list]):
            return JsonResponse({"errno": "4103",
                                 "errmsg": "必传参数错误"})

        # 3.单个检验
        if not len(title) < 64:
            return JsonResponse({"errno": "4103",
                                 "errmsg": "参数错误(title)"})

        price = int(price)
        deposit = int(deposit)
        room_count = int(room_count)
        acreage = int(acreage)
        capacity = int(capacity)
        min_days = int(min_days)
        max_days = int(max_days)

        if not len(address) < 152:
            return JsonResponse({"errno": "4103",
                                 "errmsg": "参数错误(address)"})

        if not len(unit) < 64:
            return JsonResponse({"errno": "4103",
                                 "errmsg": "参数错误(unit)"})

        if not len(beds) < 64:
            return JsonResponse({"errno": "4103",
                                 "errmsg": "参数错误(beds)"})

        try:
            # 4.保存数据
            house = House.objects.create(
                user=request.user,
                area_id=area_id,
                title=title,
                price=price,
                address=address,
                room_count=room_count,
                acreage=acreage,
                unit=unit,
                capacity=capacity,
                beds=beds,
                deposit=deposit,
                min_days=min_days,
                max_days=max_days,
            )


        # 5.返回

            # 5.保存设施信息
            # facilities = Facility.objects.filter(id__in=facility_list)
            # house.facility = facilities
            # house.save()



        except Exception as e:
            return JsonResponse({"errno": "4001",
                                 "errmsg": "数据库保存错误"})
        # 6.返回
        return JsonResponse({"errno": "0",
                             "errmsg": "发布成功",
                             "data": {"house_id": house.id}})


class IndexView(LoginRequiredMixin, View):
    def get(self, request):
        """首页房屋推荐"""
        # 获取参数
        channels = HouseImage.objects.all().order_by('-create_time')
        data_list = []
        house_list = []
        for channel in channels:
            if channel.house_id in house_list:
                continue

            data_list.append({
                "house_id": channel.house_id,
                "img_url": channel.url,
                "title": channel.house.title
            })
            house_list.append(channel.house_id)
            if len(house_list) >= 5:
                break
        return JsonResponse({
            "data": data_list,
            "errmsg": "OK",
            "errno": "0"
        })





        return JsonResponse({"errno": "0",
                             "errmsg": "发布成功",
                             "data": {"house_id": house.id}})


class MyhomeView(LoginRequiredMixin, View):
    def get(self, request):
        """我的房屋列表"""
        # 获取参数
        user = request.user
        house_list = []
        channels = House.objects.filter(user_id=user.id)
        for channel in channels:
            house_list.append({
                "address": channel.address,
                "area_name": channel.area.name,
                "ctime": channel.create_time,
                "house_id": channel.id,
                "img_url": channel.index_image_url,
                "order_count": channel.order_count,
                "price": channel.price,
                "room_count": channel.room_count,
                "title": channel.title,
                "user_avatar": channel.user.avatar
            })
        return JsonResponse({
            "data": {"houses": house_list},
            "errmsg": "OK",
            "errno": "0"
        })


class HouseInfoView(View):

    def get(self, request, house_id):
        '''房屋详情页'''

        # 1.根据house_id获取对应house
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return JsonResponse({"errno": "4001",
                                 "errmsg": "数据库查询错误"})
        if not house:
            return JsonResponse({"errno": "4002",
                                 "errmsg": "无数据"})

        # 2.根据house获取对应的评论
        try:
            orders = Order.objects.filter(house_id=house_id).order_by('-update_time')
        except Exception as e:
            return JsonResponse({"errno": "4001",
                                 "errmsg": "数据库查询错误"})
        comments_list = []
        for order in orders:
            if order.comment:
                comments_list.append({
                    "comment": order.comment,
                    "ctime": order.update_time,
                    "user_name": order.user.username
                })

        # 3.获取房屋设施信息
        try:
            facilities = house.facility.all()
        except Exception as e:
            return JsonResponse({"errno": "4001",
                                 "errmsg": "数据库查询错误"})
        facilities_list = []
        for facility in facilities:
            facilities_list.append(facility.id)

        # 4.获取房屋图片信息
        try:
            imgs = HouseImage.objects.filter(house_id=house_id)
        except Exception as e:
            return JsonResponse({"errno": "4001",
                                 "errmsg": "数据库查询错误"})
        imgs_list = []
        if imgs:
            for img in imgs:
                imgs_list.append(img.url)

        # 5.获取house的各项数据，整理成字典
        house_dict = {
            "acreage": house.acreage,
            "title": house.title,
            "price": house.price,
            "address": house.address,
            "area_id": house.area_id,
            "room_count": house.room_count,
            "unit": house.unit,
            "capacity": house.capacity,
            "beds": house.beds,
            "deposit": house.deposit,
            "min_days": house.min_days,
            "max_days": house.max_days,
            "facility": facilities_list,
            "comments": comments_list,
            "img_urls": imgs_list,
            "user_avatar": house.user.avatar,
            "user_id": house.user.id,
            "user_name": house.user.username
        }

        # 7.判断用户是否登录
        user = request.user
        if not user:
            user_id = -1
        else:
            user_id = user.id

        # 6.拼接参数
        response = JsonResponse({"data": {"house": house_dict,
                                          "user_id": user_id},
                                 "errmsg": "OK",
                                 "errno": "0"})
        # 7.返回
        return response


class SearchListView(View):
    """房屋数据搜索列表"""

    def get(self, request):
        area_id = request.GET.get('aid')
        start_day = request.GET.get('sd')
        end_day = request.GET.get('ed')
        sort_key = request.GET.get('sk')
        page = request.GET.get('p')

        # 计算时间差
        start_day = datetime.datetime.strptime(start_day, '%Y-%m-%d')
        end_day = datetime.datetime.strptime(end_day, '%Y-%m-%d')
        time_difference = (end_day - start_day).days

        # 判断排序方式
        if sort_key == 'new':
            sort_key = '-create_time'
        elif sort_key == 'booking':
            sort_key = 'order_count'
        elif sort_key == 'price-inc':
            sort_key = 'price'
        elif sort_key == 'price-des':
            sort_key = '-price'

        try:
            house = House.objects.filter(area_id=area_id).filter(Q(max_days__gt=time_difference) | Q(max_days=0)).filter(min_days__lt=time_difference).order_by(sort_key)
        except Exception as e:
            return JsonResponse({'errno': '400',
                                 'errmsg': '获取对应的房屋出错'})

        paginator = Paginator(house, 6)

        try:
            page_houses = paginator.page(page)
        except EmptyPage:
            return JsonResponse({'code': '400',
                                 'errmsg': 'page页码出错'})

        totoal_pages = paginator.num_pages

        data_list = []

        for house in page_houses:
            data_list.append({
                'address': house.address,
                'area_name': house.area.name,
                'ctime': house.create_time,
                'house_id': house.id,
                'img_url': house.index_image_url,
                'order_count': house.order_count,
                'price': house.price,
                'room_count': house.room_count,
                'title': house.title,
                'user_avatar': house.user.avatar
            })

        return JsonResponse({'data': {'houses': data_list,
                                      'total_page': totoal_pages},
                             "errmsg": "请求成功",
                             "errno": "0"})


